package cn.jekun.shop.common.service;


import java.math.BigDecimal;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpCart;
import cn.jekun.component.core.bean.gen.ErpMerchandise;
import cn.jekun.component.core.bean.gen.ErpMyShop;
import cn.jekun.component.core.bean.gen.ErpOrderLog;
import cn.jekun.component.core.bean.gen.ErpOrderMessage;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpSalePrice;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.ErpCartAttrService;
import cn.jekun.component.core.service.gen.ErpCartService;
import cn.jekun.component.core.service.gen.ErpDeliveryAddressService;
import cn.jekun.component.core.service.gen.ErpMerchandiseService;
import cn.jekun.component.core.service.gen.ErpMyShopService;
import cn.jekun.component.core.service.gen.ErpOrderItemsService;
import cn.jekun.component.core.service.gen.ErpOrderLogService;
import cn.jekun.component.core.service.gen.ErpOrderMessageService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpSalePriceService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.shop.service.PushMessageService;
import cn.jekun.component.shop.service.SendMessageService;
import cn.jekun.shop.web.bean.ErpCarts;
import cn.jekun.shop.web.bean.ErpOrder;
import cn.jekun.shop.web.bean.ErpOrderItem;
import cn.jekun.shop.web.bean.Order;
import cn.jekun.shop.web.bean.OrderItem;

@Service(OrderService.BEAN_NAME)
public class OrderService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.OrderService";

	//TODO delete me
	private static final String grdShopId="201503211939540154";//"201406242031400018";
	private static final double max = 168;//优惠的订单额度
	//END
	
	@Resource(name = cn.jekun.component.shop.service.OrderService.BEAN_NAME)
	cn.jekun.component.shop.service.OrderService orderService;
	
	@Resource(name = ErpDeliveryAddressService.BEAN_NAME)
	ErpDeliveryAddressService erpDeliveryAddressService;
	
	@Resource(name = SendMessageService.BEAN_NAME)
	private SendMessageService sendMessageService;
	
	@Resource(name=ErpCartService.BEAN_NAME)
	ErpCartService cartService;
	
	@Override
	public String getNamespace() {
		return "SHOP_ORDER";
	}
	@Resource(name=ErpOrdersService.BEAN_NAME)
	ErpOrdersService erpOrdersService;
	
	@Resource(name=ErpOrderItemsService.BEAN_NAME)
	ErpOrderItemsService erpOrderItemsService;
	
	@Resource(name=ErpOrderLogService.BEAN_NAME)
	ErpOrderLogService erpOrderLogService;
	
	@Resource(name=ErpMyShopService.BEAN_NAME)
	ErpMyShopService erpMyShopService;
	
	@Resource(name=ErpCartService.BEAN_NAME)
	ErpCartService erpCartService;
	
	@Resource(name=ErpCartAttrService.BEAN_NAME)
	private ErpCartAttrService erpCartAttrService;
	
	@Resource(name=ErpMerchandiseService.BEAN_NAME)
	ErpMerchandiseService merchandiseService;
	
	@Resource(name=ErpSalePriceService.BEAN_NAME)
	ErpSalePriceService erpSalePriceService;
	
	@Resource(name=ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	
	@Resource(name=ErpOrderMessageService.BEAN_NAME)
	ErpOrderMessageService erpOrderMessageService;
	
	@Resource(name=PushMessageService.BEAN_NAME)
	PushMessageService pushMessageService;
	
	/**
	 * 获取从购物车选择的商品信息
	 * @param cartIds 购物车代码(多个用逗号分开)
	 * @param userId 用户代码
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getOrderGooods(String userId,String cartIds){
		if (cartIds==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"购物车代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		try {
			String[] cartId = cartIds.split(",");
			Map queryMap = new HashMap();
			String whereSql="";
			for (int i = 0; i <cartId.length; i++) {
				queryMap.put("cartId", cartId[i]);
				whereSql += (i==0?"":" or")+" cart_id='"+cartId[i]+"'";
			}
			SqlUtis.prepareSql(queryMap,"and ("+whereSql+")");
			List<ErpCarts> erpCartGoods = this.list(this.getStatementName("queryCartGoodById"),queryMap);

			List<Map> data = new ArrayList();
			Map hmp = new HashMap();
			for(int i=0;i<erpCartGoods.size();i++){
				ErpCarts cart = erpCartGoods.get(i);
				String shopId = cart.getShopId();
				String shopName = cart.getShopName();
				if(!hmp.containsKey(shopId)){
					Map shopGoods = new HashMap();
					shopGoods.put("shopId", shopId);
					shopGoods.put("shopName", shopName);
					shopGoods.put("price", String.valueOf(cart.getPrice()*cart.getNums()));
					shopGoods.put("shopAddress", cart.getAddress());
					shopGoods.put("shopPhone", cart.getPhone());
					shopGoods.put("deliveryAmount", String.valueOf(cart.getDeliveryAmount()));
					shopGoods.put("businessHours",cart.getBusinessHours());
					shopGoods.put("minAmount", String.valueOf(cart.getMinAmount()));
					List lists = new ArrayList();
					lists.add(cart);
					shopGoods.put("goods", lists);		
					data.add(shopGoods);
					hmp.put(shopId, shopGoods);
				}else{
					Map shopGoods = (Map) hmp.get(shopId);
					List<ErpCarts> lists = (List) shopGoods.get("goods");
					lists.add(cart);
					String sumPrice = null;
					if(shopGoods.get("price")!=null){
						for (int j = 0; j < lists.size(); j++) {
							sumPrice = String.valueOf(Double.parseDouble(shopGoods.get("price").toString()) 
									+ lists.get(j).getPrice()*lists.get(j).getNums());
						}
					}
					shopGoods.put("price", sumPrice);
				}
			}
			
			//TODO 果然多 前2单总价大于168元，都减4元
			for (Map shopGoods : data) {
				String shopId=(String)shopGoods.get("shopId");//商家代码
				Double sumPrice = Double.parseDouble((String)shopGoods.get("price"));//总价
				if(grdShopId.equals(shopId) && sumPrice >= max){//果然多，总价大于168元 ?
					//检查是否前2单满168元
					Map countMap = new HashMap();
					countMap.put(ErpOrders.COL_SHOP_ID, shopId);
					countMap.put(ErpOrders.COL_USER_ID, userId);
					SqlUtis.prepareSql(countMap
							, SqlUtis.getSQL(countMap, ErpOrders.COL_SHOP_ID)
							, SqlUtis.getSQL(countMap, ErpOrders.COL_USER_ID)
							, " and (select sum(b.amount) from erp_order_items b where b.order_id=a.order_id  )>= "+max
							, " and a.total_amount = (select sum(b.amount) from erp_order_items b where b.order_id=a.order_id  ) - 4"
							);
					int count = this.erpOrdersService.count(countMap);
					
					if(count < 2){//购物车不存在优惠商品，前2单，则增加一个
						//更新价格
						shopGoods.put("price", sumPrice - 4);
					}
				}
			}
			//EDN
			
			jsonObject.put("data", JSONArray.fromObject(data,jsonConfig));
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	private ErpOrder findErpOrders(String shopId,List<ErpOrder> erpOrders){
		for (ErpOrder erpOrder : erpOrders) {
			if (shopId.equals(erpOrder.getShopId())) {
				return erpOrder;//已经有
			}
		}
		return null;
	}
	
	/**
	 * 是否频繁下单
	 * @param userId
	 * @param ip
	 * @return
	 */
	public boolean isAddOrderFrequently(@Security String userId, @Security String ip){
		if (StringUtils.isBlank(userId) || StringUtils.isBlank(ip)) {
			return true;
		}
    	Map existsMap = new HashMap();
    	SqlUtis.prepareSql(existsMap, " and (ip='"+ip+"' or user_id='"+userId+"') and a.create_time >= (sysdate - 2/(24*60))");
    	return this.erpOrdersService.exists(existsMap);//频繁下单
	}
	
	/**
	 * 下订单(app或web)
	 * @param shipTime 配送时间
	 * @param addressId 收货地址代码
	 * @param userId 用户代码
	 * @param paymentId 支付代码
	 * @param orderStatusId 订单状态代码
	 * @param orderTypeId 订单类型代码
	 * @param orderitemslist 订单明细
	 * @param jsonString 订单留言(app)
	 * @param orderMessagelist 订单留言(web)
	 * @param ip ip地址
	 * @return
	 */
	@Transactional
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject addOrder(
			@ErpOrders.AnnoShipTime
			String shipTime,
			@ErpOrders.AnnoAddressId
			String addressId,
			@ErpOrders.AnnoUserId
			String userId,
			@ErpOrders.AnnoPaymentId
			String paymentId,
			@ErpOrders.AnnoOrderStatusId
			String orderStatusId,
			@ErpOrders.AnnoOrderTypeId
			String orderTypeId
			,List<ErpOrderItem> orderitemslist
			,String jsonString
			,List<ErpOrderMessage> orderMessagelist
			,String ip,String terminalId,String model
			,@ErpOrders.AnnoDeliveryId String deliveryId
			){

		if(shipTime==null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"送货时间不能为空");
		}
//		if (addressId==null) {
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
//					"收货地址不能为空");
//		}
		if (userId==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户代码不能为空");
		}
		if (paymentId==null || "".equals(paymentId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"支付方式不能为空");
		}
		if (orderitemslist == null || orderitemslist.size()==0) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"订单明细不能为空");
		}
		if (deliveryId==null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"配送方式不能为空");
		}
		
		if ("2".equals(deliveryId) && !"2".equals(paymentId)) {//deliveryId=2：自提，paymentId=2：在线支付     
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"自提只能在线支付");
		}
		
		//获取支付编号
		Map payNosMap = this.oneBySql("select pk_common.get_next_id('SEQ_ERP_ORDERS_PAY_NO') PAYNO from dual");
		String payNo = "FK"+payNosMap.get("PAYNO").toString();

		//----------------------计算订单(多商家下单需要拆分订单)
		 
		Double shopMinAmount = 0.0;//起送金额
	    Double shopDeliveryAmount = 0.0;//配送费
		
		List<ErpOrder> erpOrdersList = new ArrayList<ErpOrder>();//订单集合
		
		HashSet cartSet = new HashSet();
		
		//兼容旧安卓版本(1.1.5)转入重复的cartids  
		for (int i = 0; i < orderitemslist.size(); i++) {
			cartSet.add(orderitemslist.get(i).getCartId());
		}
		Iterator<String> iterator=cartSet.iterator();
		//end 兼容旧安卓版本(1.1.5)
		
		while(iterator.hasNext()){    		//兼容前：for (int i = 0; i < orderitemslist.size(); i++) {
			try {
				String cartId = iterator.next();
				ErpCart queryerpCart = erpCartService.one(cartId);
				if (queryerpCart == null) {
					continue;//TODO 购物车不存在
				}
				String  shopId = queryerpCart.getShopId();
				Integer nums = queryerpCart.getNums();
				
				//查看商品是否已下架
				String merchandiseId = queryerpCart.getMerchandiseId();
				Map merchandiseMap = new HashMap();
				merchandiseMap.put(ErpMerchandise.COL_MERCHANDISE_ID, merchandiseId);
				merchandiseMap.put(ErpMerchandise.COL_CLOSED, Constants.GOODS_OPEN);
				SqlUtis.prepareSql(merchandiseMap,
						SqlUtis.getSQL(merchandiseMap, ErpMerchandise.COL_MERCHANDISE_ID,Types.VARCHAR,SqlUtis.EQ)
						,SqlUtis.getSQL(merchandiseMap, ErpMerchandise.COL_CLOSED,Types.VARCHAR,SqlUtis.EQ));
				ErpMerchandise merchandise = merchandiseService.one(merchandiseMap);
				if(merchandise==null){
					SqlUtis.prepareSql(merchandiseMap,
							SqlUtis.getSQL(merchandiseMap, ErpMerchandise.COL_MERCHANDISE_ID,Types.VARCHAR,SqlUtis.EQ));
					ErpMerchandise m = merchandiseService.one(merchandiseMap);
					throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
							"商品["+merchandiseId+"("+m.getMerchandiseName()+")]可能已被下架!");
				}
				
				//获取商品价格,暂时取商品价格表价格
				Map saleMap = new HashMap();
				saleMap.put(ErpSalePrice.COL_MERCHANDISE_ID, merchandiseId);
				SqlUtis.prepareSql(saleMap,SqlUtis.getSQL(saleMap, ErpSalePrice.COL_MERCHANDISE_ID,Types.VARCHAR,SqlUtis.EQ));
				ErpSalePrice erpSalePrice = erpSalePriceService.one(saleMap);
				
				Double itemAmout = new BigDecimal(erpSalePrice.getPrice() * nums).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();//单个商品总价
			    ErpOrder erpOrders = this.findErpOrders(shopId, erpOrdersList);
			    
			    if (erpOrders == null) {//拆单，创建新的订单
			    	erpOrders = new ErpOrder();
			    	erpOrders.setShopId(shopId);
			    	erpOrders.setUserId(queryerpCart.getUserId());
			    	erpOrders.setShopId(shopId); //商家Id
			    	erpOrders.setOrderStatusId(orderStatusId);
			    	erpOrders.setAddressId(addressId);
			    	erpOrders.setOrderTypeId(orderTypeId);
			    	erpOrders.setShipTime(shipTime);
			    	erpOrders.setPaymentId(paymentId);
			    	erpOrders.setPayNo(payNo); //支付编号
			    	erpOrders.setBusinessId(Constants.THIRD_BUSINESS.GENERAL_GOODS);//TODO 业务类型
			    	erpOrders.setCreateName(userId);//创建人
			    	erpOrders.setCreateTime(new Date(System.currentTimeMillis()));//创建时间
			    	erpOrders.setIp(ip);//ip地址
			    	if(StringUtils.isBlank(terminalId) && StringUtils.isBlank(model)){
			    		erpOrders.setSn("");
			    	}else{
			    		erpOrders.setSn(terminalId+" "+model);
			    	}
			    	ErpShop erpShop = erpShopService.one(shopId);
			    	shopMinAmount = erpShop.getMinAmount()==null?0.0:erpShop.getMinAmount();
			    	shopDeliveryAmount = new BigDecimal(erpShop.getDeliveryAmount()==null?0.0:erpShop.getDeliveryAmount()).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
					if (erpShop == null) {
						throw new BusinessException("商家不存在");
					}
			    	erpOrders.setShopName(erpShop.getShopName());//商家名称
			    	
			    	erpOrdersList.add(erpOrders);//增加到拆单列表
				}
				erpOrders.setNums((erpOrders.getNums()==null?0:erpOrders.getNums()) + nums);//累加
				erpOrders.setTotalAmount(new BigDecimal((erpOrders.getTotalAmount()==null?0:erpOrders.getTotalAmount()) + itemAmout).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
//				erpOrders.setPoint(Double.parseDouble(amount)); //积分规则计算
				
				//增加订单明细
				ErpOrderItem erpOrderItems = new ErpOrderItem();
				erpOrderItems.setMerchandiseId(queryerpCart.getMerchandiseId());
				erpOrderItems.setNums(nums);
				erpOrderItems.setPrice(erpSalePrice.getPrice()); //商品价格表价格
				if (erpSalePrice.getGathering()!=null) {
					erpOrderItems.setGathering(new BigDecimal(erpSalePrice.getGathering()*nums).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());//结算总价
				}
				if (erpSalePrice.getCost()!=null) {
					erpOrderItems.setCost(new BigDecimal(erpSalePrice.getCost()*nums).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());//成本总价
				}
//				erpOrderItems.setPoint(erpSalePrice.getPrice()*nums); //总积分，目前积分等于总价
				
				//币
				if (merchandise.getDdpScore()!=null) {
					erpOrderItems.setDdpScore(merchandise.getDdpScore()*nums);//商品币数量
				}
				erpOrderItems.setAmount(itemAmout);//商品总金额=价格*数量
				
				erpOrderItems.setCartId(queryerpCart.getCartId());//购物车代码
				
				erpOrderItems.setCreateName(userId);
				
				erpOrders.addErpOrderItems(erpOrderItems);//增加订单明细
				
			} catch (BusinessException e1) {
				throw e1;
			} catch (Exception e) {
				e.printStackTrace();
				throw new BusinessException("下单失败");
			}
		}
		
		//-------------------------数据库操作
		
		if (erpOrdersList == null || erpOrdersList.size()==0) {
			throw new BusinessException("下单失败");
		}
		for (int i=0;i<erpOrdersList.size();i++) {
			ErpOrder erpOrder = erpOrdersList.get(i);
			//TODO 果然多 前2单总价大于168元，都减4元
			if(grdShopId.equals(erpOrder.getShopId()) && erpOrder.getTotalAmount() >= max){//果然多，总价大于168元 ?
				//检查是否前2单满168元
				Map countMap = new HashMap();
				countMap.put(ErpOrders.COL_SHOP_ID, erpOrder.getShopId());
				countMap.put(ErpOrders.COL_USER_ID, userId);
				SqlUtis.prepareSql(countMap
						, SqlUtis.getSQL(countMap, ErpOrders.COL_SHOP_ID)
						, SqlUtis.getSQL(countMap, ErpOrders.COL_USER_ID)
						, " and (select sum(b.amount) from erp_order_items b where b.order_id=a.order_id  )>= "+max
						, " and a.total_amount = (select sum(b.amount) from erp_order_items b where b.order_id=a.order_id  ) - 4"
						);
				int count = this.erpOrdersService.count(countMap);
				
				if(count < 2){//购物车不存在优惠商品，前2单，则增加一个
					//更新价格
					erpOrder.setTotalAmount(erpOrder.getTotalAmount()-4);
				}
			}
			//END
			
			//计算是否需要配送费
			if(erpOrder.getTotalAmount()<shopMinAmount && !"2".equals(deliveryId)){//商品总金额小于起送金额，并且配送方式不是“自提”，则需要加上配送费
				erpOrder.setTotalAmount((erpOrder.getTotalAmount()==null?0:erpOrder.getTotalAmount()) + shopDeliveryAmount);
				erpOrder.setDeliveryAmount(shopDeliveryAmount);
			}
			//赋值配送方式
			erpOrder.setDeliveryId(deliveryId);
			
			
			//增加订单
			String orderId =(String)erpOrdersService.insert(erpOrder);
			//增加订单明细
			for(ErpOrderItem item : erpOrder.getItems()){
				item.setOrderId(orderId);
				String itemId = (String)this.erpOrderItemsService.insert(item);
				
				//TODO 订单属性
				Map cartArrtMap = new HashMap();
				cartArrtMap.put("cartId", item.getCartId());
				cartArrtMap.put("itemId", itemId);
				this.update("SHOP_ORDER.insertItemAttr", cartArrtMap);
				//END 订单属性
				
				//下单成功，清空购物车商品
				Map delMap = new HashMap();
				delMap.put(ErpCart.COL_CART_ID, item.getCartId());
				SqlUtis.prepareSql(delMap, SqlUtis.getSQLRequired(delMap, ErpCart.COL_CART_ID,Types.VARCHAR,SqlUtis.EQ));
				if(erpCartAttrService.exists(delMap)){
					erpCartAttrService.delete(delMap);// 删除属性
				}
				erpCartService.delete(delMap);
				//end
			}
			
			//记录订单确认日志
			ErpOrderLog erpOrderLog = new ErpOrderLog();
			erpOrderLog.setOrderId(orderId);
			erpOrderLog.setCreateName(userId);
			erpOrderLog.setMemo("订单确认");
			erpOrderLogService.insert(erpOrderLog);
			//增加订单留言(app)
			 String leaveMessage = this.getJsonValue(jsonString,"shopList",erpOrder.getShopId());
             if(StringUtils.isNotBlank(leaveMessage)){ //留言为空，则不存入留言表中
                 ErpOrderMessage erpOrderMessage = new ErpOrderMessage();
                 erpOrderMessage.setOrderId(erpOrder.getOrderId()); //订单号
                 erpOrderMessage.setCreateName(userId);
                 erpOrderMessage.setType(Constants.ERP_ORDER_MESSAGE_TYPE.ADD_ORDER);
                 erpOrderMessage.setContent(leaveMessage);//订单留言
                 erpOrderMessageService.insert(erpOrderMessage);
             }else if(orderMessagelist != null && orderMessagelist.size()>i ){//订单留言(web)
            	 ErpOrderMessage oMessage = orderMessagelist.get(i);
     			if(oMessage!=null && StringUtils.isNotBlank(oMessage.getContent())){
     				ErpOrderMessage erpOrderMessage=new ErpOrderMessage();
     				erpOrderMessage.setOrderId(erpOrder.getOrderId());
     				erpOrderMessage.setContent(oMessage.getContent());
     				erpOrderMessage.setCreateName(userId);
     				erpOrderMessage.setType(Constants.ERP_ORDER_MESSAGE_TYPE.ADD_ORDER);
     				erpOrderMessageService.insert(erpOrderMessage);
     			}
             }
             
			//增加我的商家
			Map existsMyShopMap = new HashMap();
			existsMyShopMap.put(ErpMyShop.COL_USER_ID, userId);
			existsMyShopMap.put(ErpMyShop.COL_SHOP_ID, erpOrder.getShopId());
			SqlUtis.prepareSql(existsMyShopMap, 
					SqlUtis.getSQLRequired(existsMyShopMap, ErpMyShop.COL_USER_ID),
					SqlUtis.getSQLRequired(existsMyShopMap, ErpMyShop.COL_SHOP_ID)
					);
			if(!erpMyShopService.exists(existsMyShopMap)){//判断是否存在
				ErpMyShop erpMyShop = new ErpMyShop();
				erpMyShop.setCreateName(userId);
				erpMyShop.setShopId(erpOrder.getShopId());
				erpMyShop.setUserId(userId);
				erpMyShopService.insert(erpMyShop);
			}
		}
		
		//如果是普通商品货到付款或者是普通商品在线支付(推送消息给App,pos)
		if(paymentId.equals(Constants.ERP_PAYMENT.PAYMENT_CASH_ON_DELIVERY) || paymentId.equals(Constants.ERP_PAYMENT.PAYMENT_ONLINE)){
			try {
				for (ErpOrder erpOrder :erpOrdersList) {
					ErpOrders order = this.erpOrdersService.one(erpOrder.getOrderId());
					this.sendMessageService.addOrderMessage(order);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		//--------------------------返回数据
		
		JSONArray orderInfos = new JSONArray();//订单信息(商家名称，订单号，金额)
		List<String> orderIds = new ArrayList<String>();//订单号
		double totalMoney =0;
		try {
			for (ErpOrder erpOrder : erpOrdersList) {
				
				JSONObject orderJsonObject = new JSONObject();
				
				orderJsonObject.put("shopName", erpOrder.getShopName());
				orderJsonObject.put("orderId", erpOrder.getOrderId());
				orderJsonObject.put("amount", new BigDecimal(erpOrder.getTotalAmount()).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue());
				String orderTime = DateFormatUtils.format(erpOrder.getCreateTime(), "yyyyMMddHHmmss");
				orderJsonObject.put("orderTime",orderTime);
				orderInfos.add(orderJsonObject);
				
				//
				orderIds.add(erpOrder.getOrderId());
				//
				totalMoney += erpOrder.getTotalAmount();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("payNo", payNo);
		jsonObject.put("paymentId", paymentId);
		jsonObject.put("orderIds", orderIds);
		jsonObject.put("totalMoney", totalMoney);
		jsonObject.put("orderInfos", orderInfos);
		return executeRerutn(jsonObject);
	}



	/**
	 * 取消订单
	 * @return
	 */
	public JSONObject cancelOrder(
			@NotBlank(message="用户代码不能为空") @RsUser.AnnoUserId String userId,
			@NotBlank(message="订单代码不能为空") @ErpOrders.AnnoOrderId String orderId,
			@Security
			String memo,
			@ErpOrders.AnnoCloseReason
			String reason){
		JSONObject jsonObject = new JSONObject();
		try {
			boolean result = orderService.cancelOrderByUser(userId,orderId,memo,reason);
			jsonObject.put("result", result);
		} catch(BusinessException e){
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}

	/**
	 * 获取商家/个人订单列表(app)
	 * @param shopId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getOrderByShopId(
			@Security
			String pageSize,
			@Security
			String currentPage,
			@Security
			String shopId,
			@Security
			String userId,
			@Security
			String statusId,
			Date endDate,
			boolean flag){
        
		//基本验证
		if(flag && StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"商家代码不能为空");
		}
		if(!flag && StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不能为空");
		}
				
		Page page = new Page();
		page.setPageSize(pageSize==null?10:Integer.parseInt(pageSize));
		page.setPageNumber(currentPage==null?1:Integer.parseInt(currentPage));
		JSONObject jsonObject = new JSONObject();

		try {
			Map orderMap = new HashMap();

			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
			orderMap.put("shopId", shopId);
			orderMap.put("userId", userId);
			if(StringUtils.isNotBlank(statusId)){
				orderMap.put("statusId", statusId);
			}
			if (endDate!=null) {
			   orderMap.put("date", DateFormatUtils.format(endDate,"yyyy-MM-dd"));
			}
			List<Order> orders = erpOrdersService.list(this.getStatementName("queryOrdersByShopId1"),orderMap,page);

			for (int i = 0; i < orders.size(); i++) {
				Map orderitemsMap = new HashMap();
				orderitemsMap.put("orderId", orders.get(i).getOrderId());
				List picDefault = this.list(this.getStatementName("queryGoodsPicByOrderId"),orderitemsMap);
				orders.get(i).setPicList(picDefault);
			}

			jsonObject.put("orders", JSONArray.fromObject(orders, jsonConfig));
			jsonObject.put("totalcount", page.getTotalCount());
			jsonObject.put("totalpage", page.getPages());
			jsonObject.put("pages", page.getPageNumber());

		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		return this.executeRerutn(jsonObject);
	}


	/**
	 * 获取我的订单及订单商品列表(个人)
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getMyOrderGoods(
			@Security
			String pageSize,
			@Security
			String currentPage,
			Map map){
		Page page = new Page();
		page.setPageSize(pageSize==null?10:Integer.parseInt(pageSize));
		page.setPageNumber(currentPage==null?1:Integer.parseInt(currentPage));
		JSONObject jsonObject = new JSONObject();
		try {
			List<Order> list = this.list(this.getStatementName("queryMyOrderGoodsById"),map,page);
			List data = new ArrayList();
			Map hmp = new HashMap();
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 
			for(int i=0;i<list.size();i++){
				Order order = list.get(i);
				

				String orderId = order.getOrderId();
				if(!hmp.containsKey(orderId)){
					Map orderGoods = new HashMap();
					orderGoods.put("orderId", orderId);
					orderGoods.put("orderTime", order.getOrderTime());
					orderGoods.put("shopId", order.getShopId());
					orderGoods.put("shopName", order.getShopName());
					orderGoods.put("phone", order.getPhone());
					orderGoods.put("totalAmount", order.getTotalAmount());
					orderGoods.put("orderStatusId", order.getOrderStatusId());
					orderGoods.put("orderStatus", order.getOrderStatusName());
					orderGoods.put("paymentId", order.getPaymentId());
					orderGoods.put("deliveryAmount", order.getDeliveryAmount());
					orderGoods.put("deliveryName", order.getDeliveryName());
					orderGoods.put("paymentName", order.getPaymentName()==null?"":order.getPaymentName());
					orderGoods.put("userReaded", order.getUserReaded()== null?"":order.getUserReaded());
					orderGoods.put("shopReaded", order.getShopReaded()==null?"":order.getShopReaded());
					orderGoods.put("orderTimeOut", orderService.getTimeoutMessage(order, orderService.TYPE_USER)==null?"":orderService.getTimeoutMessage(order, orderService.TYPE_USER));
					List lists = new ArrayList();
					lists.add(order);
					orderGoods.put("goods", lists);
					data.add(orderGoods);
					hmp.put(orderId, orderGoods);
				}else{
					Map orderGoods = (Map) hmp.get(orderId);
					List lists = (List) orderGoods.get("goods");
					lists.add(order);
				}
			}	
			jsonObject.put("data", JSONArray.fromObject(data,jsonConfig));
		} catch (Exception e) {
			e.printStackTrace();
			return executeRerutnFail(jsonObject);
		}
		jsonObject.put("totals", page.getTotalCount());
		jsonObject.put("pages", page.getPages());
		jsonObject.put("pageSize", page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		return executeRerutn(jsonObject);
	}



	/**
	 * 根据用户代码，获取订单列表
	 * @param userId
	 * @param status
	 * @param page
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getOrders(
			@Security
			String userId, 
			@Security
			String status, 
			
			Page page) {
		JSONObject jsonObject = new JSONObject();
		//基本验证
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户名不能为空");
		}
		try{
			JsonConfig jsonConfig = new JsonConfig();
			jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd")); 

			Map queryMap = new HashMap();
			queryMap.put("userId", userId);
			queryMap.put("status", status);
			List<Order> orders = this.list(getStatementName("selectShopOrders"), queryMap,page);
			jsonObject.put("orders", JSONArray.fromObject(orders, jsonConfig));
			jsonObject.put("totalcount", page.getTotalCount());
			jsonObject.put("totalpage", page.getPages());
			jsonObject.put("pages", page.getPageNumber());
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}

	/**
	 * 根据订单代码，获取订单商品详情
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getOrder(
			@Security
			String orderId) {
		JSONObject jsonObject = new JSONObject();
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
		//基本验证
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单代码不能为空");
		}
		try{
			//修改用户已读此订单
			ErpOrders updateOrder = new ErpOrders();
			updateOrder.setOrderId(orderId);
			updateOrder.setUserReaded("1");//1：表示此订单用户已读
			updateOrder.setUserReadedTime(new Date());
			this.erpOrdersService.update(updateOrder);
			
			Map queryMap = new HashMap();
			queryMap.put("orderId", orderId);
			String sort = "a.create_time desc nulls last";
			//订单信息
			cn.jekun.shop.app.bean.Order order = this.one(getStatementName("selectShopOrder"), queryMap);
			Double totalAmount = order.getTotalAmount()==null?0:order.getTotalAmount();
			Double deliveryAmount = order.getDeliveryAmount()==null?0:order.getDeliveryAmount();
			Double merchandiseAmount = (totalAmount - deliveryAmount)<0?0:(totalAmount - deliveryAmount);
			order.setMerchandiseAmount(merchandiseAmount);
			if (order == null) {
				throw new BusinessException("找不到订单");
			}
			jsonObject = JSONObject.fromObject(order);
			//订单商品
			List<OrderItem> items = this.list(this.getStatementName("selectShopOrderItem"), queryMap);
			jsonObject.put("items", items);
            
			
			//订单追踪
			List<Order> orderlog = this.list(this.getStatementName("selectOrderLog"), queryMap);
		
			jsonObject.put("orderlog", orderlog);

			
			//订单留言
			List<ErpOrderMessage> ordermessage = this.list(this.getStatementName("selectOrderMessage"), queryMap);
			
			jsonObject.put("ordermessage", ordermessage);
	
			
			//用户对订单的留言,最新的留言
			Map orderMsgMap= new HashMap();
			orderMsgMap.put(ErpOrderMessage.COL_ORDER_ID, orderId);
			SqlUtis.prepareSql(orderMsgMap,SqlUtis.getSQL(orderMsgMap,"a."+ErpOrderMessage.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ),
					SqlUtis.orderBy(sort));
			List<ErpOrderMessage> orderMessagesList = erpOrderMessageService.list(orderMsgMap);
			ErpOrderMessage erpOrderMessage = new ErpOrderMessage();
			if(orderMessagesList != null && orderMessagesList.size() > 0 ){
				erpOrderMessage = orderMessagesList.get(0); //获取最新的一条留言
				String createName = erpOrderMessage.getCreateName();
				String type = erpOrderMessage.getType();
				RsUser tempUser = rsUserService.one(createName);
				erpOrderMessage.setCreateName(tempUser.getUserName());
				String orderMessageType = Constants.ERP_ORDER_MESSAGE_TYPE.ADD_ORDER.equals(type)?"【用户提交订单留言】":
					Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_SHOP.equals(type)?"【商家申请客服留言】":
						Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_USER.equals(type)?"【用户申请客服留言】":
							Constants.ERP_ORDER_MESSAGE_TYPE.REJECT_RECEIPT.equals(type)?"【用户拒绝收货留言】":"";
				erpOrderMessage.setContent(orderMessageType+erpOrderMessage.getContent());
			}
			JSONArray jsonArray = JSONArray.fromObject(erpOrderMessage, jsonConfig);
//			jsonArray.get(0);
			if (jsonArray!=null && jsonArray.size()>0) {
				logger.info("===jsonObject="+jsonArray.get(0));
				jsonObject.put("erpOrderMessage", jsonArray.get(0));
			}else{
				jsonObject.put("erpOrderMessage", "");
			}

			//判断是否允许取消订单
			ErpOrders tempOrder = this.erpOrdersService.one(orderId);
			String allowCancel = "0";//allowCancelCode(0不允许取消操作   1:允许取消操作)
			if(this.orderService.allowCancelOrder(tempOrder, this.orderService.TYPE_USER)){
				allowCancel = "1";
			}
			jsonObject.put("allowCancel", allowCancel);
			//判断是否允许支付
			String allowPay = "0";
			if(this.orderService.allowPay(tempOrder)){
				allowPay = "1";
			}
			jsonObject.put("allowPay", allowPay);
			//判断是否允许提醒商家发货
			String allowRemindToShop = "0";
			if(this.orderService.allowRemind(tempOrder, this.orderService.REMIND_TO_SHOP)){
				allowRemindToShop = "1";
			}
			jsonObject.put("allowRemindToShop", allowRemindToShop);
			//判断是否允许确认收货
			String allowAcceptGoods = "0";
			if(this.orderService.allowFinishOrder(tempOrder, this.orderService.TYPE_USER)){
				allowAcceptGoods = "1";
			}
			jsonObject.put("allowAcceptGoods", allowAcceptGoods);
			//判断是否允许拒绝收货
			String allowRefuseGoods = "0";
			if(this.orderService.allowRefuse(tempOrder)){
				allowRefuseGoods = "1";
			}
			jsonObject.put("allowRefuseGoods", allowRefuseGoods);
			//判断是否允许申请客服介入
			String allowApplay = "0";
			if(this.orderService.allowApply(tempOrder)){
				allowApplay = "1";
			}
			jsonObject.put("allowApplay", allowApplay);
			//超时消息
			jsonObject.put("timeoutMessage", this.orderService.getTimeoutMessage(tempOrder, this.orderService.TYPE_USER));
			return this.executeRerutn(jsonObject);
		}catch(BusinessException e){
			throw e;
		}catch(Exception e){
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}

	/**
	 * 获得订单对象
	 * @param orderId
	 * @return
	 */
	public ErpOrders getOrderObject(@Security String orderId){
		ErpOrders order=null;
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单代码不能为空");
		}
		try{
//			Map queryMap = new HashMap();
//			queryMap.put("orderId", orderId);
			//订单信息
			order = this.erpOrdersService.one(orderId);
			if (order == null) {
				throw new BusinessException("找不到订单");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return order;
	}


	/**
	 * 支付成功，推送支付消息到终端
	 * @param payNo、支付编号
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject pushOrderByPayNo(
			@Security
			String payNo){

		JSONObject jsonObject = new JSONObject();
//		//基本验证
//		if(StringUtils.isBlank(payNo)){
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"支付编号或订单编号不能为空");
//		}
//		try {
//			Map queryMap = new HashMap();
//			if("FK".equals(payNo.substring(0,2))){
//				queryMap.put(ErpOrders.COL_PAY_NO, payNo);
//				SqlUtis.prepareSql(queryMap, SqlUtis.getSQL(queryMap, ErpOrders.COL_PAY_NO,Types.VARCHAR,SqlUtis.EQ));
//			}else{
//				queryMap.put(ErpOrders.COL_ORDER_ID, payNo);
//				SqlUtis.prepareSql(queryMap, SqlUtis.getSQL(queryMap, ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
//			}
//
//			List<ErpOrders> orders = this.erpOrdersService.list(queryMap);
//
//			//推送订单消息到终端
//			for (int s = 0; s<orders.size(); s++) {
//
//				Map terminalMap = new HashMap();
//				terminalMap.put(RsTerminal.COL_SHOP_ID, orders.get(s).getShopId());
//				terminalMap.put(RsTerminal.COL_PUSH, "1");
//				SqlUtis.prepareSql(terminalMap, SqlUtis.getSQL(terminalMap, RsTerminal.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ)
//						, SqlUtis.getSQL(terminalMap, RsTerminal.COL_PUSH,Types.VARCHAR,SqlUtis.EQ));
//				List<RsTerminal> rsTerminal = rsTerminalService.list(terminalMap);
//
//				Map erpordersMap = new HashMap();
//				erpordersMap.put(ErpOrders.COL_SHOP_ID, orders.get(s).getShopId());
//				erpordersMap.put(ErpOrders.COL_ORDER_STATUS_ID, "1");
//				SqlUtis.prepareSql(erpordersMap, SqlUtis.getSQL(erpordersMap, ErpOrders.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ)
//						, SqlUtis.getSQL(erpordersMap, ErpOrders.COL_ORDER_STATUS_ID,Types.VARCHAR,SqlUtis.EQ));
//				Integer ordersnum = erpOrdersService.count(erpordersMap);
//				if(ordersnum >=0){
//					for (int j = 0; j < rsTerminal.size(); j++) {
//						ErpOrders order = this.erpOrdersService.one(orders.get(s).getOrderId());
//						this.sendMessageService.afterPayMessage(order);
//					}
//				}
//			}
//		} catch (Exception e) {
//			return executeRerutnFail(jsonObject);
//		}
		return this.executeRerutn(jsonObject);
	}


//	/**
//	 * 订单打印(推送)
//	 */
//	@SuppressWarnings({ "rawtypes", "unchecked" })
//	public JSONObject pushOrderPrintByOrderId(
//			@Security
//			String orderId){
//		JSONObject jsonObject = new JSONObject();
//		//基本验证
//		if(StringUtils.isBlank(orderId)){
//			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单号不能为空");
//		}
//		try{
//
//			Map ordersMap = new HashMap();
//			ordersMap.put(ErpOrders.COL_ORDER_ID, orderId);
//			SqlUtis.prepareSql(ordersMap, SqlUtis.getSQL(ordersMap, ErpOrders.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ));
//			ErpOrders orders = erpOrdersService.one(ordersMap);
//			Map terminalMap = new HashMap();
//			terminalMap.put(RsTerminal.COL_SHOP_ID, orders.getShopId());
//			terminalMap.put(RsTerminal.COL_PUSH, "1");
//			SqlUtis.prepareSql(terminalMap, 
//					SqlUtis.getSQL(terminalMap,RsTerminal.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ), 
//					SqlUtis.getSQL(terminalMap, RsTerminal.COL_PUSH,Types.VARCHAR,SqlUtis.EQ));
//			List<RsTerminal> rsTerminal = rsTerminalService.list(terminalMap);
//
//			for (int j = 0; j < rsTerminal.size(); j++) {
//				JSONObject pushObject = new JSONObject();
//				pushObject.put("type", "1");//0订单数量，1订单打印
//				pushObject.put("value", orderId);
//				this.pushOrderByYunService(rsTerminal.get(j).getPushChanel(), rsTerminal.get(j).getPushUser(), 
//						pushObject.toString());
//			}
//
//		}catch (Exception e) {
//			return executeRerutnFail(jsonObject);
//		}
//		return this.executeRerutn(jsonObject);
//	}

	/**
	 * 
	* @Title: getJsonValue
	* @Description: 获取jsonObject中key
	* @param @param jsonString()
	* @param @param keys
	* @param @param key
	* @param @return    设定文件
	* @return String    返回类型
	* @throws
	 */
	public  String getJsonValue(String jsonString,String keys,String key){
		if (StringUtils.isBlank(jsonString)) {
			return null;
		}
		try{
			 JSONObject a = JSONObject.fromObject(jsonString);
		     JSONArray jsonArray =  a.getJSONArray(keys);
		     for(int i=0,length = jsonArray.size();i<length;i++){
		        	JSONObject jsonObject = jsonArray.getJSONObject(i);
		        	//System.out.println(jsonArray.size());
		        	String value1 = (String)jsonObject.get(key);
		        	if(value1 != null){
		        		return value1;
		        	}
		        }
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 提醒商家发货
	 * @param orderId
	 * @return
	 */
	public JSONObject remindToShop(@RsUser.AnnoUserId String orderId) {
		return this.orderService.remindToShop(orderId);
	}
	
	/**
	 * 用户对订单的操作
	 * @param userId
	 * @param orderId
	 * @param processCode
	 * @param processer
	 * @param reason
	 * @param fileUrl
	 * @param content
	 * @param channelId
	 * @return
	 */
	public JSONObject processOrder(String userId,String orderId,String processCode,String processer,String reason,String fileUrl,String content,String channelId){
		return this.orderService.processOrder(userId, orderId, processCode, processer, reason, fileUrl, content, channelId);
	}
	
	/**
	 * 检查订单是否允许完成
	 * @param orders
	 * @param type
	 * @return
	 */
	public boolean allowFinishOrder(ErpOrders orders, String type){
		return this.orderService.allowFinishOrder(orders, type);
	}

	/**
	 * 检查是否允许取消订单
	 * @param orders
	 * @param type
	 * @return 
	 */
	public boolean allowCancelOrder(ErpOrders orders,@Security String type){
		return this.orderService.allowCancelOrder(orders, type);
	}

	/**
	 * 是否允许做提醒操作
	 * @param orderId 订单号
	 * @param type  (1:提醒用户   2：提醒商家)
	 * @return
	 */
	public boolean allowRemind(ErpOrders orders,String type){
		return this.orderService.allowRemind(orders, type);
	}
	
	/**
	 * 是否允许拒绝收货
	 * @param orderId
	 * @return
	 */
	public boolean allowRefuse(ErpOrders orders){
		return this.orderService.allowRefuse(orders);
	}
	
	/**
	 * 是否允许申请客服介入
	 * @param orderId 订单号
	 * @return
	 */
	public boolean allowApply(ErpOrders orders){
		return this.orderService.allowApply(orders);
	}
	
	/**
	 *  根据订单号查找留言信息
	 *  @param orderId 订单号
	 *  @param page 
	 *  @return
	 *
	 */
	public JSONObject getOrderMessageByOrderId(@ErpOrderMessage.AnnoOrderId String orderId,Page page){
	    JSONObject jsonObject = new JSONObject();
		logger.info("===============OrderService getOrderMessageByOrderId begin===========");
		if(StringUtils.isBlank(orderId)){
		    throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"订单号不能为空");	
		}
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
	    String sort = "a.create_time desc nulls last";
		//用户对订单的留言,最新的留言
		Map orderMsgMap= new HashMap();
		orderMsgMap.put(ErpOrderMessage.COL_ORDER_ID, orderId);
		SqlUtis.prepareSql(orderMsgMap,SqlUtis.getSQL(orderMsgMap,"a."+ErpOrderMessage.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.orderBy(sort));
		List<ErpOrderMessage> orderMessagesList = erpOrderMessageService.list(orderMsgMap, page);
		if(orderMessagesList == null || orderMessagesList.size() == 0){
			jsonObject.put("erpOrderMessageList", "");
		}else{
		List<ErpOrderMessage> tempOrderMessages = new ArrayList<ErpOrderMessage>();
		for(int i = 0,length = orderMessagesList.size();i<length;i++){
			ErpOrderMessage erpOrderMessage = orderMessagesList.get(i);
			String type = erpOrderMessage.getType();
			String orderMessageType = Constants.ERP_ORDER_MESSAGE_TYPE.ADD_ORDER.equals(type)?"【用户提交订单留言】":
				                      Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_SHOP.equals(type)?"【商家申请客服留言】":
				                      Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_USER.equals(type)?"【用户申请客服留言】":
				                      Constants.ERP_ORDER_MESSAGE_TYPE.REJECT_RECEIPT.equals(type)?"【用户拒绝收货留言】":"";
			erpOrderMessage.setContent(orderMessageType+erpOrderMessage.getContent());
			String createName = erpOrderMessage.getCreateName();
			if(!StringUtils.isBlank(createName)){
				RsUser user = rsUserService.one(createName);
				if(user != null){
					erpOrderMessage.setCreateName(StringUtils.isNotBlank(user.getRealName())?user.getRealName():user.getUserName());	
				}
			}
			tempOrderMessages.add(erpOrderMessage);
		}
		JSONArray jsonArray = JSONArray.fromObject(tempOrderMessages, jsonConfig);
		jsonObject.put("erpOrderMessageList", jsonArray);
		}
	    return this.executeRerutn(jsonObject);
}
	
	/**
	 * 原因列表
	 * @param userId 用户编码
	 * @param processCode 操作代码
	 * @param person 操作人类型
	 * @param orderStatus 订单状态
	 * @return
	 */
	public JSONObject reasonList(@ErpOrders.AnnoUserId String userId,@Security String processCode,@Security String person,@ErpOrders.AnnoOrderId String orderId){
		return this.orderService.reasonList(userId, processCode, person, orderId);
	}
	
}